<?php defined('SYSPATH') or die('No direct script access.');

class Controller_User extends Controller_Base{

    public function action_index()
    {

        $username=$this->request->param("name");

        if(empty($username)){

            if($this->request-> is_ajax()){

                $result=array();

                $result['code']='0x00001';

                exit(json_encode($result));
            }

            $this->redirect("/");

            exit();

        }

        $user_model=new Model_User();

        $user_info=$user_model->getInfoByUserName($username);

        if(empty($user_info)){

            $this->redirect("/user/entry");

            exit();
        }

        if($this->request-> is_ajax()){

            $page=$this->request->post("page");

            $pageSize=$this->request->post("pageSize");

        }
        else{

            $page=$this->request->query("page");

            $pageSize=$this->request->query("pageSize");

        }

        $page=$page==""||$page==0?1:intval($page);

        $pageSize=$pageSize==""?20:intval($pageSize);

        $offset=$pageSize*($page-1);

        $post_model=new Model_Post();

        $listInfo=$post_model->getPostByUser($user_info['userid'],$offset,$pageSize);

        if($this->request-> is_ajax()){

            $result=array();

            $result['list']=Block_User::post_list($user_info,$listInfo['rows']);

            exit(json_encode($result));

        }

        $url="/u/".$username;

        $view=View::factory('user/index');

        $view->page=$page;

        $view->url=$url;

        $view->user_info=$user_info;

        $view->posts=$listInfo['rows'];

        $view->pages=ceil($listInfo['total']/$pageSize);

        $view->total=$listInfo['total'];

        $this->template->title = __($username);

        $this->template->content =$view;

    }
    public function action_entry(){

        $this->template->title = __('Sign In');

        $view=View::factory('user/entry');

        $this->template->content =$view;

    }
    public function action_reset(){

      $this->template->title = __('reset');

      $token=$this->request->query("token");

      if(empty($token)){

        $this->redirect('/');

        exit();

      }

      $total= DB::select(array(DB::expr('COUNT(1)'), 'total'))->from('reset_info')
      
      ->where("token",'=',$token)->limit(1)->execute()->get("total");

      if($total>0){

        $view=View::factory('user/reset');

        $view->token=$token;

        $this->template->content =$view;

      }
      else{

        $this->redirect('/');

      }

   }
    public function action_wish(){

        $username=$this->request->param("name");

        if(empty($username)){

            if($this->request-> is_ajax()){

                $result=array();

                $result['code']='0x00001';

                exit(json_encode($result));
            }

            $this->redirect("/");

            exit();

        }

        $user_model=new Model_User();

        $user_info=$user_model->getInfoByUserName($username);

        if(empty($user_info)){

            $this->redirect("/");

            exit();
        }

        $wish_model=new Model_Wish();

        $pageSize=Kohana::$config->load('item.wish')?Kohana::$config->load('item.wish'):50;

        if($this->request-> is_ajax()){

            $offset=$this->request->post("offset");

        }
        else{

            $page=$this->request->query("page");

            $page=intval($page)&&$page>=1?intval($page):1;

            $offset=$pageSize*($page-1);

        }

        $wish_list=Cache::instance()->get('wish_items'.$user_info['userid']."-".$offset, null);

        if(empty($wish_list)){

            $wish_list=$wish_model->getInfoByUser($user_info['userid'],$offset,$pageSize);

            Cache::instance()->set('wish_items'.$user_info['userid']."-".$offset, $wish_list, 100);
        }

        if($this->request-> is_ajax()){

            $result_data=array();

            foreach ($wish_list as $key => $value) {

                $data=array();

                $data[]=$value;

                $result_data[$value['id']]=Block_User::wish_list($user_info,$data);
                
            }

            $result=array();

            $result['list']=$result_data;

            exit(json_encode($result));

        }

        $total=Cache::instance()->get('wish_items'.$user_info['userid'], null);

        if(empty($total)){

            $total=$wish_model->getItemsByUser($user_info['userid']);

            Cache::instance()->set('wish_items'.$user_info['userid'], $total, 100);
        }

        $url="/u/".$username."/wish";

        $view=View::factory('user/wish');

        $view->url=$url;

        $view->user_info=$user_info;

        $view->wish_list=$wish_list;

        $view->pages=ceil($total/$pageSize);

        $view->total=$total;

        $this->template->title = __($username."-Wish");

        $this->template->content =$view;
    }
    public function action_praise(){

        $username=$this->request->param("name");

        if(empty($username)){

            if($this->request-> is_ajax()){

                $result=array();

                $result['code']='0x00001';

                exit(json_encode($result));
            }

            $this->redirect("/");

            exit();

        }

        $user_model=new Model_User();

        $user_info=$user_model->getInfoByUserName($username);

        if(empty($user_info)){

            $this->redirect("/");

            exit();
        }

        $pageSize=Kohana::$config->load('item.praise')?Kohana::$config->load('item.praise'):50;

        $user_post_model=new Model_UserPost();

        if($this->request-> is_ajax()){

            $offset=$this->request->post("offset");

        }
        else{

            $page=$this->request->query("page");

            $page=intval($page)&&$page>=1?intval($page):1;

            $offset=$pageSize*($page-1);

        }

        $posts=Cache::instance()->get('praise_list'.$user_info['userid']."-".$offset, null);

        if(empty($posts)){

            $posts=$user_post_model->getPraiseInfo($user_info['userid'],$offset,$pageSize);

            Cache::instance()->set('praise_list'.$user_info['userid']."-".$offset, $posts, 100);
        }

        if($this->request-> is_ajax()){

           $result_data=array();

            foreach ($posts as $key => $value) {

                $data=array();

                $data[]=$value;

                $result_data[$value['id']]=Block_User::praise_list($user_info,$data);
                
            }

            $result=array();

            $result['list']=$result_data;

            exit(json_encode($result));

        }

        $total=Cache::instance()->get('praise_items'.$user_info['userid'], null);

        if(empty($total)){

            $total=$user_post_model->getPraiseItems($user_info['userid']);

            Cache::instance()->set('praise_items'.$user_info['userid'], $total, 100);
        }

        $url="/u/".$username."/praise";

        $view=View::factory('user/praise');

        $view->url=$url;

        $view->user_info=$user_info;

        $view->posts=$posts;

        $view->pages=ceil($total/$pageSize);

        $view->total=$total;

        $this->template->title = __($username."-Praise");

        $this->template->content =$view;
    }
    public function action_review(){

        $username=$this->request->param("name");

        if(empty($username)){

            if($this->request-> is_ajax()){

                $result=array();

                $result['code']='0x00001';

                exit(json_encode($result));
            }

            $this->redirect("/");

            exit();

        }

        $user_model=new Model_User();

        $user_info=$user_model->getInfoByUserName($username);

        if(empty($user_info)){

            $this->redirect("/");
            exit();
        }
        
        $pageSize=Kohana::$config->load('item.review_post')?Kohana::$config->load('item.review_post'):50;

        $user_post_model=new Model_UserPost();

        if($this->request-> is_ajax()){

            $offset=$this->request->post("offset");

        }
        else{

            $page=$this->request->query("page");

            $page=intval($page)&&$page>=1?intval($page):1;

            $offset=$pageSize*($page-1);

        }

        $posts=Cache::instance()->get('review_post'.$user_info['userid']."-".$offset, null);

        if(empty($posts)){

            $posts=$user_post_model->getReviewInfo($user_info['userid'],$offset,$pageSize);

            Cache::instance()->set('review_post'.$user_info['userid']."-".$offset, $posts, 100);
        }

        if($this->request-> is_ajax()){

            $result_data=array();

            foreach ($posts as $key => $value) {

                $data=array();

                $data[]=$value;

                $result_data[$value['id']]=Block_User::review_list($user_info,$data);
                
            }

            $result=array();

            $result['list']=$result_data;

            exit(json_encode($result));

        }

        $total=Cache::instance()->get('review_items'.$user_info['userid'], null);

        if(empty($total)){

            $total=$user_post_model->getReviewItems($user_info['userid']);

            Cache::instance()->set('review_items'.$user_info['userid'], $total, 100);
        }

        $url="/u/".$username."/review";

        $view=View::factory('user/review');

        $view->url=$url;

        $view->user_info=$user_info;

        $view->posts=$posts;

        $view->pages=ceil($total/$pageSize);

        $view->total=$total;

        $this->template->title = __($username."-Review");

        $this->template->content =$view;
    }

    public function action_setting(){

        $user=Session::instance()->get('user');

        if(empty($user)){

            $this->redirect("/user/entry");

            exit();

        }

        $model_user=new Model_User();

        $userInfo=$model_user->getInfoByUserId($user['userid']);

        $view=View::factory('user/setting');

        $view->userInfo=$userInfo;

        if($this->request-> is_ajax()){

            $result=array();

            $result['data']=$view->render();

            exit(json_encode($result));

        }


        $this->template->content =$view;

    }

    public function action_upload_photo(){

        $user=Session::instance()->get('user');

        $result=array();

        if(!empty($user)){

            $userid=$user['userid'];

            $name=$this->request->post("name");

            $file=$_FILES[$name];

            $filepath=$file['tmp_name'];
       
            $filename=$file['name'];

            if (preg_match("/[\x7f-\xff]/", $filename)){

                $img_name=$userid."-temp".date('Ymd').rand(1,9999);

            }

            $img_name=$userid."-".date('Ymd').rand(1,9999).$filename;

            $upFilePath ='temp/photo/'.$img_name;

            $model_common=new Model_Common();

            $r=$model_common->upload_file($filepath,$upFilePath,'');

            if($r){

                try {

                    $sql="update site_user set photo='/".$upFilePath."' where  site_userid='$userid'";
                    
                    $total_rows=DB::query(null,$sql)->execute();

                    Database::instance()->commit();

                }

                catch (Exception $e) {

                    Database::instance()->rollback();
                    
                }

                $result['photo_image']="/".$upFilePath;

                $result['code']='0x00000';
                
            }
            else{

                $result['info']="对不起，上传失败";
            }

        }

        else{

            $result['code']='0x00001';
        }

        exit(json_encode($result));
    }

    public function action_logout(){

      Session::instance()->set('user','');

      if(empty($_SERVER['HTTP_REFERER'])){

        $this->redirect("");

      }

      $this->redirect($_SERVER['HTTP_REFERER']);

    }

    public function action_saveProfile(){

        $user=Session::instance()->get('user');

        $result=array();

        if(!empty($user)){

            $userid=$user['userid'];

            $username=$this->request->post("username");

            $about=$this->request->post("about");

            if(empty($username)){

                $result['code']='0x0000x';
                $result['info']='用户名不能为空';
            }

            else{

                try {

                    Database::instance()->begin();

                    $total_rows=DB::update('site_user')

                    ->set(array('fullname'=>$username,'about'=>$about))

                    ->where('site_userid','=',$userid)->execute();

                    Database::instance()->commit();

                    $result['code']='0x00000';

                }

                catch (Exception $e) {

                    Database::instance()->rollback();

                    $result['code']='0x0000x';
                    
                }

            }

        }

        else{

            $result['code']='0x00001';
        }

        exit(json_encode($result));
    }

    public function action_saveLogin(){

        $user=Session::instance()->get('user');

        $result=array();

        if(!empty($user)){

            $old_password=$this->request->post("old_password");

            if(empty($old_password)){

                $result['code']='0x0000x';
                $result['info']='当前密码不能为空';
                exit(json_encode($result));
            }

            $new_password=$this->request->post("new_password");

            if(empty($new_password)){

                $result['code']='0x0000x';
                $result['info']='新密码不能为空';
                exit(json_encode($result));
            }

            $userid=$user['userid'];

            $user_model=new Model_User();

            $result=$user_model->saveLogin($userid,$old_password,$new_password);

        }

        else{

            $result['code']='0x00001';
        }

        exit(json_encode($result));
    }
}
?>